package cn.wei.reallyEnjoy.user.activity;

import androidx.annotation.Nullable;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import cn.wei.reallyEnjoy.R;
import cn.wei.reallyEnjoy.app.LoginActivity;
import cn.wei.reallyEnjoy.app.RecordDetailActivity;
import cn.wei.reallyEnjoy.utils.Constants;
import cn.wei.reallyEnjoy.utils.KeyboardUtils;
import okhttp3.Call;


public class WriteDiaryActivity extends AppCompatActivity implements View.OnClickListener {


    private static int RESULT_LOAD_IMAGE = 10;
    private ImageButton ibWriteBack;
    private ImageView ivWriteContentImg;
    private Button btnWriteDiarySelectImg;
    private EditText etWriteDiaryTitle;
    private EditText etWriteDiaryContent;
    private Button btnWriteDiaryCommit;
    private String uid;
    private String imgUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_diary);
        //去掉窗口标题
        getSupportActionBar().hide();
        SharedPreferences sp = this.getSharedPreferences("user", MODE_PRIVATE);
        findViews();
        checkUser();
    }

    private void checkUser() {
        SharedPreferences sp = this.getSharedPreferences("user", MODE_PRIVATE);
        uid = sp.getString("id", "");
        if (TextUtils.isEmpty(uid)){
            Toast.makeText(this, "未登录,请先登录", Toast.LENGTH_SHORT).show();
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent=new Intent(WriteDiaryActivity.this, LoginActivity.class); //使用getActivity得到当前Activity
                            startActivity(intent);
                            finish(); //销毁当前Activity（即一直按back返回也不会回到前一个Activity，直接回到桌面）

                        }
                    })
                    .setCancelable(false)
                    .show();
            return;
        }
    }

    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2021-12-01 14:40:39 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        ibWriteBack = (ImageButton)findViewById( R.id.ib_write_back );
        ivWriteContentImg = (ImageView)findViewById( R.id.iv_write_content_img );
        btnWriteDiarySelectImg = (Button)findViewById( R.id.btn_writeDiary_selectImg );
        etWriteDiaryTitle = (EditText)findViewById( R.id.et_writeDiary_title );
        etWriteDiaryContent = (EditText)findViewById( R.id.et_writeDiary_content );
        btnWriteDiaryCommit = (Button)findViewById( R.id.btn_writeDiary_commit );

        ibWriteBack.setOnClickListener( this );
        btnWriteDiarySelectImg.setOnClickListener( this );
        btnWriteDiaryCommit.setOnClickListener( this );
    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2021-12-01 14:40:39 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == ibWriteBack ) {
            // Handle clicks for ibWriteBack
            finish();
        } else if ( v == btnWriteDiarySelectImg ) {
            // Handle clicks for btnWriteDiarySelectImg
            //点击事件，而重定向到图片库
            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            //android6.0之后不仅需要在Mainfest里面添加权限，还需要添加运行时权限。
            //这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()方法。
            //我们需要判断requestCode是否是我们之前传给startActivityForResult()方法的RESULT_LOAD_IMAGE，并且返回的数据不能为空
            if (ActivityCompat.checkSelfPermission(WriteDiaryActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(WriteDiaryActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }

            startActivityForResult(intent, RESULT_LOAD_IMAGE);
        } else if ( v == btnWriteDiaryCommit ) {
            // Handle clicks for btnWriteDiaryCommit
            String DiaryTitle = etWriteDiaryTitle.getText().toString().trim();
            String DiaryContent = etWriteDiaryContent.getText().toString().trim();
            if (TextUtils.equals(imgUrl,"")){
                Toast.makeText(WriteDiaryActivity.this, "请选择图片", Toast.LENGTH_SHORT).show();
                return;
            }

            else if (TextUtils.equals(DiaryTitle,"")){
                Toast.makeText(WriteDiaryActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            else if (TextUtils.equals(DiaryContent,"")){
                Toast.makeText(WriteDiaryActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
                return;

            }
            else if(!TextUtils.equals(imgUrl,"")){
                String url = Constants.WRITE_DIARY_URL;
                OkHttpUtils.post()
                        .url(url)
                        .addParams("uid",uid)
                        .addParams("contentImg",imgUrl)
                        .addParams("title",DiaryTitle)
                        .addParams("content",DiaryContent)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Toast.makeText(WriteDiaryActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                JSONObject jsonObject = JSON.parseObject(response);
                                String code = String.valueOf(jsonObject.get("code"));
                                if (TextUtils.equals(code,"0")){
                                    Toast.makeText(WriteDiaryActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                    finish();
                                }else{
                                    Toast.makeText(WriteDiaryActivity.this, "发布失败，服务器错误", Toast.LENGTH_SHORT).show();
                                }



                            }
                        });
            }
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    //重写启动新的activity以后的回调方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            //查询我们需要的数据
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            Log.e("picturePath",picturePath);

            String fileName = picturePath.split("/")[picturePath.split("/").length - 1];
           Log.e("fileName",fileName);
            cursor.close();
            ivWriteContentImg.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            String url = Constants.FILE_UPLOAD_URL;

            File file = new File(picturePath);
            OkHttpUtils.post()
                    .url(url)
                    .addFile("file", fileName, file)//
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Toast.makeText(WriteDiaryActivity.this, "网络错误,图片上传失败", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            JSONObject jsonObject = JSON.parseObject(response);
                            String code = String.valueOf(jsonObject.get("code"));
                            if (TextUtils.equals(code,"0")){
                                imgUrl = String.valueOf(jsonObject.get("data"));
                                Log.e("imgUrl",imgUrl);
                                Glide.with(WriteDiaryActivity.this).load(Constants.BASE_URL+imgUrl).into(ivWriteContentImg);

                            }else{
                                Toast.makeText(WriteDiaryActivity.this, "服务器错误,图片上传失败", Toast.LENGTH_SHORT).show();
                            }

                        }
                    });




        }


    }
}